<template>
  <div class="announcement-container">
    <div style="width: 50%;margin: 5px;">
      <el-card class="announcement-box">
        <div class="announcement-header">
          <h3>最新公告</h3>
        </div>
        <div class="announcement-content">
          <p>{{ announcements.currentAnnouncement }}</p>
        </div>
      </el-card>
      <el-card style="margin-top: 5px;">
        <div ref="tu1" style="height: 400px; margin-top: 40px;"></div>
        <el-switch
          v-model="state"
          inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          active-text="曲线开启状态"
          inactive-text="曲线关闭状态"
          :active-action-icon="View"
          :inactive-action-icon="Hide"
          @change="handleSwitchChange"
        />
      </el-card>
    </div>
    <el-card 
    style="width: 50%; height: 605px; margin: 5px auto; padding: 20px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);"
    body-style="padding: 20px;"
    >
    <div>
      <p style="font-size: 30px;margin: 10px;">公告栏</p>
      <p class="gd" @click="gd">查看更多→</p>
    </div>
  <div 
    v-for="(at, index) in anctList" 
    :key="index" 
    class="list">
    <router-link :to="{ path: '/home/details', query: { id:at.id }}">
      <span style="width: 25px; height: 25px; background-color: #f0f0f0; display: inline-block; text-align: center; line-height: 25px; margin-right: 10px; border-radius: 4px;">
        {{ index + 1 }}
      </span>
      <span style="color: #333; font-size: 16px; font-weight: 500;">{{ at.title }}</span>
    </router-link>
  </div>
</el-card>
  </div>
</template>

<script setup>
import { Hide, View } from '@element-plus/icons-vue'
import { ref, onMounted, onBeforeUnmount  } from 'vue';
import { selectAnct,selectFaBu } from '@/api/announcemt';
import * as echarts from 'echarts';
import router from '@/router';
const tu1=ref(null)
let mytu1={}

// 响应式状态
const gd=async()=>{
  router.push("/home/moreancts")
}
const announcements = ref({
  list: [
  ],
  currentAnnouncement: '',
  announcementIndex: 0,
  setIntervalId: null
});
const anctList=ref([])
const res=ref(null)
// 方法区
const anct = async () => {
  try {
    //左侧公告
    const response = await selectAnct(5);
    if (response && response.data && response.data.data) {
      res.value = response.data.data;
      // 清空公告列表
      announcements.value.list = [];
      // 添加默认公告
      // announcements.value.list.unshift('请及时关注公告信息');
      // 检查 res.value 是否有 array 属性
      if (res.value && Array.isArray(res.value)) {
        res.value.forEach((element) => {
          if (element.title) {
            announcements.value.list.unshift("关于《"+element.title+"》已发布");
          }
        });
      }
    } else {
      ElMessage.error("公告数据格式不正确！");
    }
    //右侧公告
    anctList.value = (await selectAnct(10)).data.data;
  } catch (error) {
    ElMessage.error("公告获取失败！");
    console.error(error); // 打印错误信息，方便调试
  }
};
const switchAnnouncement = () => {
  announcements.value.currentAnnouncement = announcements.value.list[announcements.value.announcementIndex];
};

const startCarousel = () => {
  announcements.value.setIntervalId = setInterval(() => {
    announcements.value.announcementIndex = (announcements.value.announcementIndex + 1) % announcements.value.list.length;
    switchAnnouncement();
  }, 3000); // 每3秒切换一次公告
};
let option = {
  title: {
    text: '近日发布数量趋势图',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      const date = new Date(params[0].axisValue);
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}<br/>${params[0].seriesName}: ${params[0].value[1]}`;
    }
  },
  xAxis: {
    type: 'time',
    name: '日期',
    nameLocation: 'middle',
    nameGap: 25,
    axisLabel: {
      interval: 0, // 强制显示所有标签
      formatter: function (value) {
        const date = new Date(value);
        return `${date.getMonth() + 1}/${date.getDate()}`;
      },
      rotate: 0 // 如果标签过长，可以旋转显示
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed'
      }
    },
    boundaryGap: ['2%', '2%']
  },
  yAxis: {
    type: 'value',
    name: '发布数量',
    nameLocation: 'middle',
    nameGap: 30,
    axisLabel: {
      formatter: '{value}'
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed'
      }
    },
    // 设置 Y 轴的最小值和最大值
    min: 0, // 设置 Y 轴最小值
    max: 15, // 设置 Y 轴最大值
    interval: 3 // 设置 Y 轴刻度间隔
  },
  series: [
    {
      name: '发布数量',
      type: 'line',
      //曲
      smooth:false,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        width: 3,
        color: '#5470c6'
      },
      itemStyle: {
        color: '#5470c6'
      },
      data: [
      ]
    }
  ],
  grid: {
    left: '5%',
    right: '4%',
    bottom: '15%', // 增加底部空间，避免标签被裁剪
    containLabel: true
  }
};
const selectTu= async ()=>{
  let list=[]
  const response=await selectFaBu()
  const sfb=response.data.data
  console.log("sfb:");
  console.log(sfb);
  sfb.forEach((element) => {
    list.push([new Date(element.publishDate).getTime(), element.count])    
  });
  // console.log(list);
  //数据导入
  option.series[0].data=list
  if (mytu1) {
    mytu1.setOption(option);
  }
}
//曲率控制
const state=ref(false)
// 定义开关变化时的处理方法
const handleSwitchChange = (value) => {
  // 样式控制
  option.series[0].smooth=value
  if (mytu1) {
    mytu1.setOption(option);
  }
};
// 生命周期
onMounted(() => {
  //初始化图
  selectTu();

  anct();
  switchAnnouncement(); // 初始化当前公告
  startCarousel(); // 启动轮播
  
  //图
   mytu1=echarts.init(tu1.value)
   mytu1.setOption(option);
  // 添加窗口大小变化监听
  window.addEventListener('resize', () => {
    mytu1.resize();
  });
});

onBeforeUnmount(() => {
  clearInterval(announcements.value.setIntervalId); // 清除定时器
  window.removeEventListener('resize', () => {
    tu1.resize();
  });
  if (mytu1) {
    mytu1.dispose();
  }
});
</script>

<style scoped>
.list{
  padding: 10px; display: flex; align-items: center;
}
.list:hover{
  background-color: #eaeaea;
}
.gd{
  float: right;
}
.gd:hover{
  cursor: pointer;
}
.wz{
  margin-top: 20px;
  .el-row{
    margin: 10px;
    display: flex;
    justify-content: space-around;
    .el-card{
      width: 48%;
    }
  }
}
a{
  color: black ;
  text-decoration:none ;
}
/* 最外层 */
.announcement-container {
  width: 100%;
  display: flex;
}

.announcement-box {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  padding: 15px;
  text-align: center;
  transition: all 0.3s ease;
}

.announcement-header h3 {
  color: #67c23a;
  font-size: 1.2rem;
  margin-bottom: 10px;
}

.announcement-content p {
  color: #409eff;
  font-size: 1rem;
  font-weight: bold;
  animation: fadeIn 1s ease-in-out;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
</style>